//格式化时间
function dateFtt(fmt,date)
{ //author: meizz
  var o = {
    "M+" : date.getMonth()+1,                 //月份
    "d+" : date.getDate(),                    //日
    "h+" : date.getHours(),                   //小时
    "m+" : date.getMinutes(),                 //分
    "s+" : date.getSeconds(),                 //秒
    "q+" : Math.floor((date.getMonth()+3)/3), //季度
    "S"  : date.getMilliseconds()             //毫秒
  };
  if(/(y+)/.test(fmt))
    fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));
  for(var k in o)
    if(new RegExp("("+ k +")").test(fmt))
  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
  return fmt;
}
function formatSubscribeTime(cellValue, options, rowObject) {
	var dateStr = "";
	if(cellValue){
		var crtTime = new Date(cellValue);
		dateStr = dateFtt("yyyy-MM-dd hh:mm:ss",crtTime);
	}
    return dateStr;
}
//加载字典
function dictJudge(value, options, row){
    //sex为自定义字典项
	var statusObj = vm.options.sex;
    for( var i=0;i< statusObj.length;i++ ){
        if(statusObj[i].value == value){
            return '<span>'+statusObj[i].text+'</span>' ;
        }
    }
}

function getRootPath(){
    //获取当前网址，如： http://localhost:8083/uimcardprj/share/meun.jsp
    var curWwwPath=window.document.location.href;
    //获取主机地址之后的目录，如： uimcardprj/share/meun.jsp
    var pathName=window.document.location.pathname;
    var pos=curWwwPath.indexOf(pathName);
    //获取主机地址，如： http://localhost:8083
    var localhostPaht=curWwwPath.substring(0,pos);
    //获取带"/"的项目名，如：/uimcardprj
    var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);
    return(localhostPaht+projectName);//http://localhost:8083/uimcardprj
}

$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'news/topic/list',
        datatype: "json",
        colModel: [
			{ label: '序号', name: 'id', index: 'id', width: 15, key: true },
            { label: '编辑者', name: 'author', index: 'author', width: 25 },
            { label: '公告类型', name: 'cname', index: 'cname', width: 25 },
            { label: '发布时间', name: 'publishDate', index: 'publish_date', width: 30,
                formatter:
                    function(cellvalue, options, row){
                        return dateFtt("yyyy-MM-dd",new Date(cellvalue))
                 }
                    },
            { label: '发布状态', name: 'status', index: 'status', width: 25,
                formatter: function (cellvalue, options, rowObject) {
                    return cellvalue == 1 ? "已发布" : "未发布";
                }
            },
            { label: '标题', name: 'title', index: 'title'}
        ],
		viewrecords: true,
        height: 385,
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page",
            rows:"limit",
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
        }
    });
    vm.getChannels();

    $("#q-channel-select").mouseover(function () {
        $("#q-channel-select").val(null);
        console.log(666);
        vm.getChannels();
    });
});


function datePlugin(){
    //初始化日期组件-年月日
    $('#publish_date').datepicker({
        language: 'zh-CN',//显示中文
        startView: 0, //选择器开始界面 0：天（默认 1：月2：年3：十年 4：世纪
        minViewMode: 0,//最小选择精度 0：天（最小默认）
        maxViewMode: 2, //最大选择精度 4：世纪（最大默认）
        format: 'yyyy-mm-dd',//显示格式
        minView: "day",//设置只显示到月份
        // initialDate: new Date(),
        autoclose: true,//选中自动关闭
        // todayBtn: true//显示今日按钮
        clearBtn: true, //清除按钮
        todayHighlight: true //今日高亮
    });
}


var vm = new Vue({
	el:'#rrapp',
	data:{
        q:{
            channel: ''
        },
		showList: true,
		title: null,
		topic: {
            status:'',
            cid:''
        },
        channels:{}
	},
	methods: {
		query: function () {
			vm.reload();
		},
        reset: function(){
            vm.q.channel = '';
        },
		add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.topic = {};

			vm.getChannels();

			datePlugin();
			//设置默认日期
            vm.topic.publishDate = dateFtt('yyyy-MM-dd',new Date());

            // 富文本编辑器--发布内容
            //  var ue = UE.getEditor('editor');
             UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
             UE.Editor.prototype.getActionUrl = function(action) {
                 if (action == 'uploadimage' || action == 'uploadscrawl' || action == 'uploadimage'
                     || action == 'uploadvideo' || action == 'uploadfile') {
                     // return '${pageContext.request.contextPath}/ueditor/upload';
                     return getRootPath() + '/common/file/upload/ueSaveFile';
                 }else {
                     return this._bkGetActionUrl.call(this, action);
                 }
             };

            //先清空文件上传
            $('#myFile').fileinput('clear');
            //清除
            $('#myFile').fileinput('destroy');
            //手机缩略图
            $("#myFile").fileinput({
                language : 'zh',
                uploadUrl : baseURL + "common/file/upload/saveFile",
                autoReplace : true,
                showUpload: false,
                maxFileCount : 1,
                allowedFileExtensions : [ "jpg", "png", "gif" ],
                browseClass : "btn btn-primary", //按钮样式
                previewFileIcon : "<i class='glyphicon glyphicon-king'></i>",
                layoutTemplates:{
                    actionUpload:'',//去除上传预览缩略图中的上传图片
                    // actionZoom:'',   去除上传预览缩略图中的查看详情预览的缩略图标
                    // actionDownload:'', //去除上传预览缩略图中的下载图标
                    actionDelete:'', //去除上传预览的缩略图中的删除图标
                },//对象用于渲染布局的每个部分的模板配置。您可以设置以下模板来控制窗口小部件布局.eg:去除上传图标
                initialPreview: function () {
                    var logo = vm.topic.logo;
                    if (logo===undefined || logo==null || logo===''){
                        return [];
                    }
                    return ["<img src='"+logo+"' class='file-preview-image' style='height: 100%;' alt='logo'/>"];
                }()

            }).on("filebatchselected", function(event, files) {
                $(this).fileinput("upload");
            }).on("fileuploaded", function(e, data) {
                var res = data.response;
                // console.log(222);
                // console.log(res);
                /* alert(res.success); */
                vm.topic.logo=res.fileList[0].url;
            });
		},
		update: function (event) {
			var id = getSelectedRow();
			if(id == null){
				return ;
			}
			vm.showList = false;
            vm.title = "修改";

            datePlugin();
            vm.getInfo(id);
            vm.getChannels();

            // 富文本编辑器--发布内容
            //  var ue = UE.getEditor('editor');
            UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
            UE.Editor.prototype.getActionUrl = function(action) {
                if (action == 'uploadimage' || action == 'uploadscrawl' || action == 'uploadimage'
                    || action == 'uploadvideo' || action == 'uploadfile') {
                    // return '${pageContext.request.contextPath}/ueditor/upload';
                    return getRootPath() + '/common/file/upload/ueSaveFile';
                }else {
                    return this._bkGetActionUrl.call(this, action);
                }
            };

            //清除
            $('#myFile').fileinput('destroy');
            //手机缩略图
            $("#myFile").fileinput({
                language : 'zh',
                uploadUrl : baseURL + "common/file/upload/saveFile",
                autoReplace : true,
                showUpload: false,
                maxFileCount : 1,
                allowedFileExtensions : [ "jpg", "png", "gif" ],
                browseClass : "btn btn-primary", //按钮样式
                previewFileIcon : "<i class='glyphicon glyphicon-king'></i>",
                layoutTemplates:{
                    actionUpload:'',//去除上传预览缩略图中的上传图片
                    // actionZoom:'',   去除上传预览缩略图中的查看详情预览的缩略图标
                    // actionDownload:'', //去除上传预览缩略图中的下载图标
                    actionDelete:'', //去除上传预览的缩略图中的删除图标
                },//对象用于渲染布局的每个部分的模板配置。您可以设置以下模板来控制窗口小部件布局.eg:去除上传图标
                initialPreview: function () {
                    var logo = vm.topic.logo;
                    if (logo===undefined || logo==null || logo===''){
                        return [];
                    }
                    return ["<img src='"+logo+"' class='file-preview-image' style='height: 100%;' alt='logo'/>"];
                }()

            }).on("filebatchselected", function(event, files) {
                $(this).fileinput("upload");
            }).on("fileuploaded", function(e, data) {
                var res = data.response;
                // console.log(222);
                // console.log(res);
                /* alert(res.success); */
                vm.topic.logo=res.fileList[0].url;
            }).on('filecleared', function() {
                console.log('filecleared');
                vm.topic.logo = '';
                console.log(vm.topic);
            });
        },
		saveOrUpdate: function (event) {
			var url = vm.topic.id == null ? "news/topic/save" : "news/topic/update";

			//作者判空
            if(vm.topic.author==null||vm.topic.author==''){
                alert("请输入作者！！");
                return ;
            }
            //类型判空
            if(vm.topic.cid==null||vm.topic.cid==''){
                alert("请选择公告类型！！");
                return ;
            }
            //标题判空
            if(vm.topic.title==null||vm.topic.title==''){
                alert("请输入标题！！");
                return ;
            }
            //发布时间
            var publish_date = $("#publish_date").val();
            if (publish_date == null || publish_date == ''){
                alert("请选择发布时间！！");
                return;
            }
            vm.topic.publishDate = publish_date;
            //状态判空
            if(vm.topic.status==null){
                alert("请选择发布状态！！");
                return ;
            }

            var ue = UE.getEditor('editor');
            vm.topic.content =encodeURI(ue.getContent());
            console.log("content---"+vm.topic.content);

            $.ajax({
				type: "POST",
			    url: baseURL + url,
                contentType: "application/json",
			    data: JSON.stringify(vm.topic),
			    success: function(r){
			    	if(r.code === 0){
						alert('操作成功', function(index){
							vm.reload();
						});
						console.log("JSONtopic-----"+JSON.stringify(vm.topic));
					}else{
						alert(r.msg);
                        console.log(JSON.stringify(vm.topic));

                    }
				}
			});
		},
		del: function (event) {
			var ids = getSelectedRows();
			if(ids == null){
				return ;
			}

			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "news/topic/delete",
                    contentType: "application/json",
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},

        getInfo: function(id){
            $.ajaxSettings.async = false;
            $.get(baseURL + "news/topic/info/"+id, function(r){
                vm.topic = r.topic;
                console.log("content:"+vm.topic.content);
                console.log("content:"+typeof(vm.topic.content));
                console.log("before:"+vm.topic.content);
                vm.topic.content = vm.topic.content.replace(/&amp;nbsp;/ig,' ');
                console.log("after:"+vm.topic.content);
                vm.topic.logo =r.topic.logo;
                console.log("vm.topic.logo--"+ vm.topic.logo);
                //日期格式化
                vm.topic.publishDate = dateFtt("yyyy-MM-dd",new Date(vm.topic.publishDate));

                //富文本编辑器--发布内容
                // var ue = UE.getEditor('editor');
                UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
                UE.Editor.prototype.getActionUrl = function(action) {
                    if (action == 'uploadimage' || action == 'uploadscrawl' || action == 'uploadimage'
                        || action == 'uploadvideo' || action == 'uploadfile') {
                        return getRootPath() + '/common/file/upload/ueSaveFile';
                    }else {
                        return this._bkGetActionUrl.call(this, action);
                    }
                };
                ue.ready(function(){//监听编辑器实例化完成的事件
                    ue.setContent("");
                    ue.setContent(vm.topic.content);
                });

            });
            $.ajaxSettings.async = true;
		},

        //获取所有公告类型
        getChannels: function(){
            $.get(baseURL + "news/channel/list", function(r){
                vm.channels = r.page.list;

            });
        },

		reload: function (event) {
			vm.showList = true;
			ue.setContent("");
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{
                postData:{'cname': vm.q.channel},
                page:page
            }).trigger("reloadGrid");
		}
	}
});

vm.getChannels();